<template>
  <BlueBackground>
    <van-cell-group inset>
      <van-uploader :after-read="methods.onUploadUserImg">
        <van-cell title="头像" center>
          <template #right-icon>
            <div class="user-icon">
              <img :src="imgBase" alt="用户头像" @error="onLoadError" />
            </div>
          </template>
        </van-cell>
      </van-uploader>
      <van-cell title="用户id" center :value="userId" />
      <van-cell title="昵称" center>
        <template #right-icon>
          <input class="inp" type="text" v-model="nickName" />
        </template>
      </van-cell>
      <van-cell title="简介" center>
        <template #right-icon>
          <input class="inp" type="text" v-model="desc" />
        </template>
      </van-cell>
    </van-cell-group>
  </BlueBackground>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import BlueBackground from '@/components/BlueBackground.vue'
import { GET, PUT } from '@/api'
import { UploaderFileListItem } from 'vant'
import { onBeforeRouteLeave } from 'vue-router'
import { uploadImage } from '@/utils/upload'

const imgBase = ref<string | undefined>('')
const userId = ref('')
const nickName = ref('')
const desc = ref('')

const methods = {
  getMyMessage() {
    GET({
      url: '/user/info'
    })
      .then((res) => {
        imgBase.value = import.meta.env.VITE_APP_PROXY_URL + res.data.userImg
        userId.value = res.data.id
        nickName.value = res.data.username
        desc.value = res.data.desc || '这家伙很懒,什么都没有留下'
      })
      .catch((err) => {
        console.error(err)
      })
  },
  onUploadUserImg(file: UploaderFileListItem | UploaderFileListItem[]) {
    const _file = file as UploaderFileListItem
    imgBase.value = _file.content
    // const imgType = _file.file?.type.split('/')[1]
    // const serverBase64Img = _file.content?.replace(
    //   /^data:image\/[A-Za-z]+;base64,/,
    //   ''
    // )
    // 上传图片不得大于10MB
    if (_file.file && _file.file.size > 10 * 1024 * 1024) {
      showFailToast('上传图片不得大于10MB')
      return
    }
    if (!_file.file) return
    showLoadingToast({
      duration: 0,
      forbidClick: true,
      message: '图片上传中...'
    })
    uploadImage({
      url: '/user/upload/avatar',
      file: _file.file
    })
      .then((res) => {
        imgBase.value = import.meta.env.VITE_APP_PROXY_URL + res.data.userImg
      })
      .catch(console.error)
      .finally(closeToast)
  }
}

const onSave = () => {
  console.log('保存')
  PUT({
    url: '/user/info',
    params: {
      username: nickName.value,
      desc: desc.value
    }
  })
}

// 图片加载失败
const onLoadError = () => {
  const defaultUrl = import.meta.env.VITE_APP_PROXY_URL + '/defaultImgs/bg.png'
  if (imgBase.value === defaultUrl) return
  imgBase.value = defaultUrl
}

onMounted(() => {
  methods.getMyMessage()
})
// 离开当前路由
onBeforeRouteLeave(() => {
  onSave()
  return true
})
</script>

<style lang="less" scoped>
:deep(.van-uploader__input-wrapper) {
  width: 343px;
}
.user-icon {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  overflow: hidden;
  position: relative;
  //   :deep(.van-uploader__input-wrapper) {
  //     width: 40px;
  //     height: 40px;
  //   }
  img {
    width: 100%;
    height: 100%;
  }
}
.inp {
  border: none;
  outline: none;
  text-align: right;
}

.custom-title {
  margin-right: 4px;
  vertical-align: middle;
}

.search-icon {
  font-size: 16px;
  line-height: inherit;
}
</style>
